import pymysql




def show_tables(**args):
    conn = pymysql.connect(host = args["host"], user = args["user"], password = args["password"], database=args["db"], port=int(args["port"]), autocommit=True)
    

    cur = conn.cursor()

    sql = f'show tables from {args["db"]}'
    rows = cur.execute(sql)
    # print(f'一共有 {rows} 张表')

    result = []
    for d in cur.fetchall():
       result.append(d[0])

    cur.close()
    conn.close()

    return result


def desc_mysql_fields(**args):
    # conn = pymysql.connect(args["host"], args["user"],args["password"],args["db"], port=int(args["port"]))
    conn = pymysql.connect(host = args["host"], user = args["user"], password = args["password"], database=args["db"], port=int(args["port"]))
    cur = conn.cursor()

    # 执行SQL查询语句获取表的结构信息
    query = f"DESCRIBE {args['table_name']}"
    cur.execute(query)

    # 获取查询结果
    result = cur.fetchall()

    # 解析表的结构信息，提取字段的格式
    res = []
    for row in result:
        # print(row)
        field_name = row[0]
        field_type = row[1]

        res.append({
            "name": field_name,
            "type": field_type,
        })

    cur.close()
    conn.close()
   

    return res


    